import {Component, OnInit} from "@angular/core";
import {Router} from "@angular/router";
import {UserService, User} from "./user.service";
@Component({
    templateUrl: 'app/modules/user/html/user.list.html',
})
export class UserListComponent implements OnInit {
    errorMessage:string;
    users:User[];

    constructor(private router:Router,
                private service:UserService) {
    }

    ngOnInit() {
        this.getUsers();
    }

    onSelect(user:User) {
        this.router.navigate(['/user', user.id]);
    }

    getUsers() {
        this.service.getUsers()
            .subscribe(
                users => this.users = users,
                error => this.errorMessage = <any>error);
    }

    delUser(id:number) {
        this.service.delUser(id).subscribe(data=>this.removeUser(data), error => this.errorMessage = <any>error);
    }

    removeUser(id:number) {
        for (var i = 0; i < this.users.length; i++) {
            if (this.users[i].id == id) {
                this.users.splice(i,1);
            }
        }
    }

    addUser(name:string) {
        if (!name) {
            return;
        }
        this.service.addUser(name)
            .subscribe(
                user => this.users.push(user),
                error => this.errorMessage = <any>error);
    }

}